using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ScriptBehind.Core;
using ScriptBehind.Core.Interfaces;
using ScriptBehind.Extensions;

namespace ScriptBehind.Scripts
{
    public sealed class RemoteFileScript : ScriptBase
    {
        public string OriginalPath { get; set; }
        public string Content { get; set; }

        public override IInjectionFormatter Formatter
        {
            get { return new RemoteFileInjectionFormatter(); }
        }

        public override void TryConstruct(string from)
        {
            if (from.ToLower().StartsWith("http://"))
                FromUrl(from);
        }

        RemoteFileScript(string orginalPath, string filename, InjectPosition injectPosition) 
        {
            OriginalPath = orginalPath;
            FileName = filename;
            InjectPosition = injectPosition;
        }

        public static RemoteFileScript FromUrl(string path)
        {
            return FromUrl(path, InjectPosition.Default);
        }

        public static RemoteFileScript FromUrl(string path, InjectPosition injectPosition)
        {
            return FromUrl(new Uri(path), injectPosition);
        }

        public static RemoteFileScript FromUrl(Uri path)
        {
            return FromUrl(path, InjectPosition.Default);
        }

        public static RemoteFileScript FromUrl(Uri path, InjectPosition injectPosition)
        {
            if (path.Scheme.ToLower() != "http") throw new ArgumentException("Supplied path is invalid, only http is accepted.", "path");
            return new RemoteFileScript(path.OriginalString, path.AbsolutePath.Trim('/'), injectPosition);
        }

    }

    public class RemoteFileInjectionFormatter : InjectionFormatter
    {
        public RemoteFileInjectionFormatter()
            : base("<script type='text/javascript' src='{0}'></script>")
        {
        }

        public override string Format(IScript script, bool seperate)
        {
            var typedScript = script as RemoteFileScript;

            if (typedScript == null)
                return null;

            return seperate
                       ? InjectionFormatString.FormatWith(typedScript.OriginalPath)
                       : typedScript.OriginalPath;
        }

        public override string Format(IEnumerable<IScript> scripts, bool seperate)
        {
            return scripts == null ? null : scripts.Select(x => Format(x, seperate)).Join("\r\n");
        }
    }
}